<!-- 登录页面 -->
<template>
  <div class="flex items-center justify-center h-full bg-gradient-to-br from-primary/90 to-secondary/90 p-4">
    <div
        class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-8 transform transition-all duration-300 hover:scale-[1.01]">
      <div class="text-center mb-8">
        <h3 class="text-[clamp(1.25rem,2.5vw,1.75rem)] font-bold text-gray-900">FreeChat</h3>
        <p class="text-gray-500 mt-2">与世界保持联系</p>
      </div>

      <form class="space-y-4">
        <div>
          <label for="username" class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
          <div class="relative">
                  <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                    <i class="fa fa-user"></i>
                  </span>
            <input
                type="text"
                id="username"
                v-model="loginForm.username"
                class="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all duration-300"
                placeholder="请输入用户名"
                required/>
          </div>
        </div>

        <div>
          <label for="password" class="block text-sm font-medium text-gray-700 mb-1">密码</label>
          <div class="relative">
                  <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500">
                    <i class="fa fa-lock"></i>
                  </span>
            <input
                type="password"
                id="password"
                v-model="loginForm.password"
                class="w-full pl-10 pr-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-all duration-300"
                placeholder="请输入密码"
                required/>
            <button type="button" @click="() => {passwordVisible=!passwordVisible}"
                    class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-500">
              <i :class="passwordVisible ? 'fa fa-eye-slash' : 'fa fa-eye'"></i>
            </button>
          </div>
        </div>

        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <input id="remember-me" type="checkbox" v-model="rememberMe"
                   class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
            <label for="remember-me" class="ml-2 block text-sm text-gray-700">记住我</label>
          </div>
          <a href="#" class="text-sm font-medium text-blue-600 hover:text-blue-500 transition-colors"
             @click="()=>{router?.replace({path: '/demo'})}">忘记密码?</a>
        </div>

        <button type="button" @click.prevent="clickLogin"
                class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-lg transition-all duration-300 transform hover:scale-[1.02] active:scale-[0.98] shadow-lg hover:shadow-xl flex items-center justify-center">
          <span>登录</span>
          <i class="fa fa-arrow-right ml-2"></i>
        </button>
      </form>

      <div class="mt-6 text-center">
        <p class="text-gray-600">
          还没有账号?
          <button @click="emits('togglePane', 'register')"
                  class="font-medium text-blue-600 hover:text-blue-500 transition-colors">立即注册
          </button>
        </p>
      </div>

    </div>
  </div>
</template>
<script setup lang="ts">
import {ElMessage} from "element-plus";
import 'element-plus/es/components/message/style/css';
import {defineEmits, ref, inject, watch} from "vue";

import {useRouter} from 'vue-router';
import {useLoginStore} from '../../stores/login_store.ts'
import {useChatStore} from '../../stores/chating_store.ts'
import {useContactStore} from '../../stores/contacts_store.ts'

import LoginApi from '../../api/login.js';
import {User} from "@/models/chat_model.ts";

const emits = defineEmits([
  "togglePane"
])

const signalWS = inject('signalWS');
const chatWS = inject('chatWS');

const router = useRouter()

const loginStore = useLoginStore()
const chatStore = useChatStore()
const contactStore = useContactStore()

let passwordVisible = ref(false);
/*暂存 rememberMe的值*/
const rememberMe = ref(localStorage.getItem("freechat:rememberMe")=='1');
watch(rememberMe, (newVal, oldVal) => {
  console.log(`newVal = ${newVal} , oldVal = ${oldVal}`);
  localStorage.setItem("freechat:rememberMe",newVal?'1':'');
})

let loginForm = ref({
  username: '',
  password: ''
});

/**
 * 登录
 * 调用登录请求接口 ——> 保存登录用户信息+token数据 ——>跳转到Home页面
 */
const clickLogin = async () => {
  const account = loginForm.value.username;
  const password = loginForm.value.password;

  if (account && password) {
    console.debug("调用登录请求...")
    let resp = await LoginApi.logIn(account, window.btoa(password), "");

    const loginUser = new User({
      uid: resp.data.userInfo.id,
      username: resp.data.userInfo.username,
      nickname: resp.data.userInfo.nickname,
      avatarUrl: resp.data.userInfo.avatarUrl
    });
    const tokenData = {
      accessToken: resp.data.access_token,
      refreshToken: resp.data.refresh_token,
      uid: resp.data.userInfo.id,
    }
    //存储登录用户信息、token信息
    loginStore.saveUserInfo(loginUser, tokenData);

    //回调main线程
    window.ipcRenderer?.loginCallback(tokenData,rememberMe.value);

    await chatStore.reloadData(loginUser);
    await contactStore.refreshContactsGroups();
    await contactStore.refreshApplyList();

    toHome();

    chatWS?.connect(tokenData.accessToken);
    signalWS?.connect(tokenData.uid); //peer连接
  } else {
    ElMessage.warning("username 或password不能为空")
  }

}

/**
 * 路由到主页面
 */
const toHome = () => {
  router?.replace({path: '/'})
}
</script>
<style scoped>

</style>